package com.party.admin.task;

import com.google.common.collect.Maps;
import com.party.common.utils.DateUtils;
import com.party.core.model.member.*;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberMerchantCountService;
import com.party.core.service.member.IMemberMerchantDetailService;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 合作商消息提醒
 *
 * @author yifeng
 * @date 2018/9/6 0006
 * @time 下午 15:56
 */
@Component("quartzNotifyPartner")
public class QuartzNotifyPartner {
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IMemberMerchantDetailService memberMerchantDetailService;
    @Autowired
    private IMemberMerchantCountService memberMerchantCountService;
    @Autowired
    private IOfficialPartnerNotifySendService officialPartnerNotifySendService;

    Logger logger = LoggerFactory.getLogger(getClass());

    private static DecimalFormat df2 = new DecimalFormat("#.##");

    private static final String ALLOW_IP = "10.135.165.181";
    /**
     * 通知昨天 每天早上8点
     */
    public void notifyYesterday() {
        /*String ip = null;
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            ip = address.getHostAddress();//192.168.0.121
            logger.info("当前服务的ip地址是{}", ip);
        } catch (UnknownHostException e) {
            logger.error("获取当前服务的IP异常", e);
        }
        if (StringUtils.isNotEmpty(ip) && !ALLOW_IP.equals(ip)) {
            return;
        }*/
        String date = DateUtils.formatDate(new Date(), "MM月dd日") + "00时00分";
        List<MemberGroup> partners = memberGroupService.getAllPartnerWithName();

        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        //昨日
        String day = DateUtils.formatDate(DateUtils.addDay(new Date(), -1));
        memberMerchantDetailQuery.setCreateStart(day);
        memberMerchantDetailQuery.setCreateEnd(day);

        for (MemberGroup member : partners) {
            memberMerchantDetailQuery.setMemberId(member.getId());
            try {
                // 总数
                MemberMerchantCount count = memberMerchantCountService.findByMemberIdSum(member.getId(), true);

                // 详情
                MemberMerchantDetail detail = memberMerchantDetailService.sum(memberMerchantDetailQuery);

                Double money = null == detail ? 0 : detail.getMoney();
                String moneyFormat = df2.format(money);

                Double totalMoney = null == count ? 0 : count.getMoney();
                String totalMoneyFormat = df2.format(totalMoney);

                if (money < 1000d) {
                    continue;
                }

                Map<String, Object> map = Maps.newHashMap();
                map.put("{money}", moneyFormat);
                map.put("{totalMoney}", totalMoneyFormat);
                map.put("{date}", date);
                map.put("{partnerName}", member.getRealname());

                String sms = String.format("[资金提醒]截止%s，您的累计资金为%s元，昨天收入%s元。",
                        date, totalMoneyFormat, moneyFormat);

                String app = String.format("[%s]截止%s，您的累计资金为%s元，昨天收入%s元。",
                        member.getRealname(), date, totalMoneyFormat, moneyFormat);

                logger.info("sms：" + sms);
                logger.info("app" + app);

                officialPartnerNotifySendService.notifyYesterday(map, member.getId(), member.getMobile());

            } catch (Exception e) {
                logger.error("通知昨天 每天早上8点 资金提醒异常 机构名称：{}", e, member.getRealname());
                continue;
            }
        }
    }

    /**
     * 通知上周 每周一早上8点
     */
    public void notifyLastWeek() {
        /*String ip = null;
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            ip = address.getHostAddress();//192.168.0.121
            logger.info("当前服务的ip地址是{}", ip);
        } catch (UnknownHostException e) {
            logger.error("获取当前服务的IP异常", e);
        }
        if (StringUtils.isNotEmpty(ip) && !ALLOW_IP.equals(ip)) {
            return;
        }*/
        Date startTime = DateUtils.getFirstDayOfWeek(-1);
        Date endTime = DateUtils.getLastDayOfWeek(-1);

        String start = DateUtils.formatDate(startTime, "MM.dd");
        String end = DateUtils.formatDate(endTime, "MM.dd");

        MemberMerchantDetailQuery query = new MemberMerchantDetailQuery();
        query.setCreateStart(DateUtils.formatDate(startTime));
        query.setCreateEnd(DateUtils.formatDate(endTime));

        List<MemberGroup> partners = memberGroupService.getAllPartnerWithName();
        for (MemberGroup member : partners) {
            query.setMemberId(member.getId());
            try {
                // 总数
                MemberMerchantCount count = memberMerchantCountService.findByMemberIdSum(member.getId(), true);

                // 详情
                MemberMerchantDetail detail = memberMerchantDetailService.sum(query);

                Double money = null == detail ? 0 : detail.getMoney();
                String moneyFormat = df2.format(money);

                Double totalMoney = null == count ? 0 : count.getMoney();
                String totalMoneyFormat = df2.format(totalMoney);

                if (money <= 0d) {
                    continue;
                }

                Map<String, Object> map = Maps.newHashMap();
                map.put("{money}", moneyFormat);
                map.put("{totalMoney}", totalMoneyFormat);
                map.put("{date}", start + "-" + end);
                map.put("{partnerName}", member.getRealname());

                String sms = String.format("[资金提醒]上周（%s）收入%s元，您的累计资金为%s元。",
                        start + "-" + end, moneyFormat, totalMoneyFormat);

                String app = String.format("[%s]上周（%s）收入%s元，您的累计资金为%s元。",
                        member.getRealname(), start + "-" + end, moneyFormat, totalMoneyFormat);

                logger.info("sms：" + sms);
                logger.info("app" + app);

                officialPartnerNotifySendService.notifyLastWeek(map, member.getId(), member.getMobile());
            } catch (Exception e) {
                logger.error("通知上周 每周一早上8点 资金提醒异常 机构名称：{}", e, member.getRealname());
                continue;
            }
        }
    }

    /**
     * 通知上月 每月1号早上8点
     */
    public void notifyLastMonth() {
        /*String ip = null;
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            ip = address.getHostAddress();//192.168.0.121
            logger.info("当前服务的ip地址是{}", ip);
        } catch (UnknownHostException e) {
            logger.error("获取当前服务的IP异常", e);
        }
        if (StringUtils.isNotEmpty(ip) && !ALLOW_IP.equals(ip)) {
            return;
        }*/
        Date startTime = DateUtils.getFirstDayOfMonth(-1);
        Date endTime = DateUtils.getLastDayOfMonth(-1);

        String start = DateUtils.formatDate(startTime, "MM.dd");
        String end = DateUtils.formatDate(endTime, "MM.dd");

        String month = DateUtils.formatDate(startTime, "M月");

        List<MemberGroup> partners = memberGroupService.getAllPartnerWithName();

        MemberMerchantDetailQuery query = new MemberMerchantDetailQuery();
        query.setCreateStart(DateUtils.formatDate(startTime));
        query.setCreateEnd(DateUtils.formatDate(endTime));

        for (MemberGroup member : partners) {
            query.setMemberId(member.getId());
            try {
                // 总数
                MemberMerchantCount count = memberMerchantCountService.findByMemberIdSum(member.getId(), true);

                MemberMerchantDetailWithMember detail = memberMerchantDetailService.sum(query);

                Double money = null == detail ? 0 : detail.getMoney();
                String moneyFormat = df2.format(money);

                Double totalMoney = null == count ? 0 : count.getMoney();
                String totalMoneyFormat = df2.format(totalMoney);

                if (money <= 0d) {
                    continue;
                }

                Map<String, Object> map = Maps.newHashMap();
                map.put("{money}", moneyFormat);
                map.put("{totalMoney}", totalMoneyFormat);
                map.put("{date}", start + "-" + end);
                map.put("{partnerName}", member.getRealname());
                map.put("{month}", month);

                String sms = String.format("[资金提醒]上月（%s）收入%s元，您的累计资金为%s元。",
                        start + "-" + end, moneyFormat, totalMoneyFormat);

                String app = String.format("[%s]%s（%s）收入%s元，您的累计资金为%s元。",
                        member.getRealname(), month, start + "-" + end, moneyFormat, totalMoneyFormat);

                logger.info("sms：" + sms);
                logger.info("app" + app);

                officialPartnerNotifySendService.notifyLastMonth(map, member.getId(), member.getMobile());
            } catch (Exception e) {
                logger.error("通知上月 每月1号早上8点 资金提醒异常 机构名称：{}", e, member.getRealname());
                continue;
            }
        }
    }
}